<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var findUnsortedSubarray = function (nums) {
      const copied = nums.slice(0).sort((a, b) => a - b)
      let i = 0
      let j = nums.length - 1
      while (copied[i] === nums[i] && i < nums.length) {
        i++
      }
      while (copied[j] === nums[j] && j >= 0) {
        j--
      }
      if (i >= j) {
        return 0
      }
      return j - i + 1
    };
    console.log(findUnsortedSubarray([2, 6, 4, 8, 10, 9, 15]));
  </script>
</body>

</html>